package com.api;

/**
 * 单点认证接口代码示例
 * Created by YeShengtao on 2020/9/29 0:00
 */

import com.alibaba.fastjson.JSON;
import com.customization.entity.Result;
import com.google.common.collect.Maps;
import com.weaver.qfengx.RequestUtils;
import com.weaver.qfengx.StringUtils;
import okhttp3.Response;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.Map;

@Path("seconddev/case/sso")
public class SsoApi {

    @GET
    @Path("/login")
    @Produces(MediaType.APPLICATION_JSON)
    public String login(@Context HttpServletRequest request,
                        @Context HttpServletResponse response) throws IOException {
        String loginid = request.getParameter("loginid");
        if (StringUtils.isEmpty(loginid)) {
            return JSON.toJSONString(Result.paramErr());
        }
        // 与登录平台进行验证是否已登录
//        boolean isLogin = false;
//        if (!isLogin) {
//            return JSON.toJSONString(Result.fail("未登录"));
//        }
        // 模拟登录获取token
        String oaHost = "http://localhost:89"; // 修改为对应环境的OA地址
        Map<String, String> params = Maps.newHashMap();
        params.put("appid", ""); // 统一认证配置的appid
        params.put("loginid", loginid);
        Response resp = RequestUtils.doGet(oaHost + "/ssologin/getToken", params);
        if (resp.isSuccessful() && resp.code() == 200) { // 获取到token
            String token = resp.body().string();
            // 重定向到门户地址
            response.sendRedirect(oaHost + "/wui/index.html?ssoToken=" + token + "#/main");
            return "";
        } else {
            return JSON.toJSONString(Result.fail("登录失败"));
        }
    }


}
